#!/usr/bin/env python
#-*-coding: utf-8 -*-
# author: weiyf    data:2015/05/16

version = '0.0.1'

description =  '''
                file format:
                    1.1.1.1
                    3.3.3.3
                    2.2.2.2
                '''

def netcheck():
    '''
        check your network
        return 1    -->    OK
        return 0    -->    Bad
    '''
    from socket import socket,AF_INET,SOCK_STREAM
    test = socket(AF_INET,SOCK_STREAM)
    try: 
        test.connect(('cip.cc',80))
    except:
        test.close()
        return 0
    test.close()
    return 1

def searchip(textfile):
    '''
        searchip(testfile): return ip   (list)
        if return 0   -->   file read failed    (int)
        if return None    -->    IP Not Found   (str)
    '''
    import re
    try:
        f = open(textfile).read()
    except:
        return 0
    data = set(re.findall(r'(?<![\.\d])(?:\d{1,3}\.){3}\d{1,3}(?![\.\d])',f))

    if not data:
        return 'None'
    return data

def ip2addr(ip,timeout=3):
    '''
        ip2addr(str(ip),[default timeout=3]): 
        return address  (str)
    '''
    import urllib2
    import re
    timeout = int(timeout)
    api = 'http://www.cip.cc/'
    try:
        data = urllib2.urlopen(api+ip,timeout=timeout).read()
    except KeyboardInterrupt,e:
        exit(1)
    except:
        return '暂时无法解析'
    return re.findall(r'地址.*',data)[1].split(':')[1]

def ip2domain(ip):pass

def domain2ip(domain):
    '''
        domain2ip(domain):  return ip address (str)
    '''
    import socket
    try:
        result = socket.getaddrinfo(domain,None)
    except:
        return 0
    return result

def getdelay(ip):
    '''
        getiprrt(ipaddress): return network delay (str)
        if No network return None
    '''
    import os,re
    import platform
    plat = platform.system()
    count = 3
    timeout = 1

    if plat == 'Windows':
        data = os.popen('ping -n %s -w %s %s' % (count,timeout,ip)).readlines()
        if '100%' in data[-1]:
            return 'None'
        else:
            return data[-1].split()[-1][:-2]

    try:
        data = os.popen('/bin/ping -c %s -W %s %s' % (count,timeout,ip) ).readlines()
        if data[-1] == '\n':
            return 'None'
        else:
            return data[-1].split('/')[4]
    except KeyboardInterrupt:
        exit(4)


if __name__ == '__main__':
    print 'This is a module, please import first'
